import 'package:get/get.dart';
import 'package:wallet_utils/base_router_config.dart';
import 'package:wallet_utils/event_bus_utils.dart';
import 'package:wallet_utils/login_utils.dart';
import 'package:wallet_utils/msg_event_utils.dart';
import 'package:wallet_utils/report_widget/base/callback/base_callback.dart';
import 'package:wallet_utils/toast.dart';
import 'package:wallet_utils/webview_common.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../home/home_page/logic.dart';
import '../api/mine_api.dart';
import '../bean/mineInfoBean.dart';
import '../bean/productInfoBean.dart';
import 'state.dart';

class MinePageLogic extends GetxController {
  final MinePageState state = MinePageState();
  DataInfo? mineInfo;
  num? indexStatus = 1;
  List<HomeProductList> productList = [];
  final homeLogic = Get.put(HomePageLogic());
  final homeState = Get.find<HomePageLogic>().state;

  @override
  void onInit() async {
    super.onInit();
    state.isLogin = await LoginUtils.isLogin();

    EventBusUtils.getInstance().on<MsgEventBusUtils>().listen((event) async {
      state.isLogin = await LoginUtils.isLogin();
      if (state.isLogin) {
        if (event.type == MsgEventBusUtils.upMineStatus) {
          getUserInfo();
        }
      }
    });
    if (state.isLogin) {
      getUserInfo();
    }
  }

  void mineCheck(int index) {
    switch (index) {
      case 0:
        Get.toNamed(BaseRouterConfig.aboutUs);
        break;
      case 1:
        Get.toNamed(BaseRouterConfig.contactService);
        break;
      case 2:
        Get.toNamed(BaseRouterConfig.setting);
        break;
    }
  }

  void payInfo(String name) {
    switch (name) {
      case '我要还款':
        Get.toNamed(BaseRouterConfig.repayment);
        break;
      case '贷款记录':
        Get.toNamed(BaseRouterConfig.loanRecord);
        break;
    }
  }

  void contact(String name) {
    switch (name) {
      case '拨打电话':
        // ignore: deprecated_member_use
        Get.back();
        launch("tel:${mineInfo?.onlineServiceMobile}");
        break;
      case '联系客服':
        Get.back();
        Get.to(WebViewCommon(
          mineInfo?.onlineServiceUrl ?? '',
        ));
        break;
    }
  }

  ///产品列表
  getUserInfo() {
    MineApi.getUserInfo(BaseCallback(onSuccess: (map) {
      MineInfoBean mineInfoBean = MineInfoBean.fromJson(map);
      if (mineInfoBean.data != null) {
        mineInfo = mineInfoBean.data;
        update();
      }
    }, onError: (msg) {
      Future.delayed(const Duration(milliseconds: 500), () {
        ToastUtils.showToast(msg ?? "");
      });
    }));
  }

  bool isShow() {
    bool show = false;
    if (homeState.indexStatus == 1 &&
        homeState.productList!.isNotEmpty &&
        homeLogic.isShowIncoming) {
      show = true;
    } else {
      show = false;
    }
    return show;
  }
}
